/**
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain an copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.littlejie.circleprogress.utils;

import ohos.agp.components.Component;
import ohos.agp.render.Paint;

/**
 * 数据转换工具类
 *
 * @author fuchi
 * @since 2021-04-02
 */
public class MiscUtil {

    /**
     * 测量 View
     *
     * @param measureSpec
     * @param defaultSize View 的默认大小
     * @return int
     */
    public static int measure(int measureSpec, int defaultSize) {
        int result = defaultSize;
        int specMode = Component.MeasureSpec.getMode(measureSpec);
        int specSize = Component.MeasureSpec.getSize(measureSpec);

        if (specMode == Component.MeasureSpec.PRECISE) {
            result = specSize;
        } else if (specMode == Component.MeasureSpec.NOT_EXCEED) {
            result = Math.min(result, specSize);
        }
        return result;
    }

    /**
     * 获取数值精度格式化字符串
     *
     * @param precision
     * @return string
     */
    public static String getPrecisionFormat(int precision) {
        return "%." + precision + "f";
    }

    /**
     * 反转数组
     *
     * @param arrays
     * @param <T>
     * @return T
     */
    public static <T> T[] reverse(T[] arrays) {
        if (arrays == null) {
            return null;
        }
        int length = arrays.length;
        for (int i = 0; i < length / 2; i++) {
            T t = arrays[i];
            arrays[i] = arrays[length - i - 1];
            arrays[length - i - 1] = t;
        }
        return arrays;
    }

    /**
     * 测量文字高度
     * @param paint
     * @return double
     */
    public static double measureTextHeight(Paint paint) {
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        return DecimalUtils.sub(Math.abs(fontMetrics.ascent), fontMetrics.descent);
    }
}